import 'dart:async';
import 'package:flutter/material.dart';

void main() {
  var onError = FlutterError.onError;
  FlutterError.onError = (FlutterErrorDetails details) {
    onError?.call(details);
    // ... 处理上报逻辑，此处是flutter自己捕获的异常
  };

  runZoned(() => runApp(const MyApp()),
      // 异常配置
      zoneSpecification: ZoneSpecification(
        // 捕获打印
        print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
          // ...收集日志
          // ...
          // 打印 此处可判断是否是debug模式下，如果是再打印
          parent.// print(zone, "Interceptor: $line");
        },
        // 捕获未处理的异步异常
        handleUncaughtError: (self, parent, zone, error, stackTrace) {
          parent.// print(zone, '${error.toString()} $stackTrace');
          // 处理异常
          // 。。。
        },
      ));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
            seedColor: const Color.fromARGB(255, 66, 157, 218)),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'APP Name'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('nihao')),
      body: InheritedWidgetTestRoute(),
    );
  }
}

class ShareDataWidget extends InheritedWidget {
  ShareDataWidget({
    Key? key,
    required this.data,
    required Widget child,
  }) : super(key: key, child: child);

  final int data; //需要在子树中共享的数据，保存点击次数

  //定义一个便捷方法，方便子树中的widget获取共享数据
  static ShareDataWidget? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<ShareDataWidget>();
  }

  //该回调决定当data发生变化时，是否通知子树中依赖data的Widget重新build
  @override
  bool updateShouldNotify(ShareDataWidget old) {
    return old.data != data;
  }
}

class _TestWidget extends StatefulWidget {
  @override
  __TestWidgetState createState() => __TestWidgetState();
}

class __TestWidgetState extends State<_TestWidget> {
  @override
  Widget build(BuildContext context) {
    // print("__TestWidgetState build");
    //使用InheritedWidget中的共享数据
    return Text(ShareDataWidget.of(context)!.data.toString());
  }

  @override //下文会详细介绍。
  void didChangeDependencies() {
    super.didChangeDependencies();
    //父或祖先widget中的InheritedWidget改变(updateShouldNotify返回true)时会被调用。
    //如果build中没有依赖InheritedWidget，则此回调不会被调用。
    // print("Dependencies change");
  }
}

class InheritedWidgetTestRoute extends StatefulWidget {
  @override
  _InheritedWidgetTestRouteState createState() =>
      _InheritedWidgetTestRouteState();
}

class _InheritedWidgetTestRouteState extends State<InheritedWidgetTestRoute> {
  int count = 0;
  final BarController _controller = BarController();

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ShareDataWidget(
        //使用ShareDataWidget
        data: count,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(bottom: 20.0),
              child: _TestWidget(), //子widget中依赖ShareDataWidget
            ),
            ElevatedButton(
              child: const Text("Increment"),
              //每点击一次，将count自增，然后重新build,ShareDataWidget的data将被更新
              onPressed: () => setState(() => ++count),
            ),
            Bar(
              controller: _controller,
            ),
            ElevatedButton(
                onPressed: () {
                  _controller.count.value = 1;
                  _controller.font.value = 30;
                },
                child: const Text('加满'))
          ],
        ),
      ),
    );
  }
}

// 手写一个controller
// class BarController extends ChangeNotifier {
//   BarController(this._value);
//   double _value = 0.5;

//   double get value => _value;
//   set value(double val) {
//     _value = val;
//     notifyListeners();
//   }
// }

// 使用ValueNotifier写一个controller 不需要继承 ChangeNotifier
class BarController {
  ValueNotifier<double> count = ValueNotifier(0.5);
  ValueNotifier<double> font = ValueNotifier(14);
}

class Bar extends StatefulWidget {
  const Bar({Key? key, required this.controller}) : super(key: key);
  final BarController controller;
  @override
  _BarState createState() => _BarState();
}

class _BarState extends State<Bar> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.yellow,
      child: ListenableBuilder(
          listenable: Listenable.merge(
              [widget.controller.count, widget.controller.font]),
          builder: (BuildContext context, Widget? child) => Column(children: [
                FlutterLogo(
                  size: widget.controller.count.value * 100 + 50,
                ),
                Slider(
                    value: widget.controller.count.value,
                    onChanged: (val) => {widget.controller.count.value = val}),
                Text(
                  "data",
                  style: TextStyle(fontSize: widget.controller.font.value),
                )
              ])),
    );
  }
}
